package voip.directory.client;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

import cs252.voip.R;
import voip.directory.OPERATIONS;
import voip.directory.Packet;
import voip.directory.User_Entry;
import voip.main.MainActivity;
import voip.ringer.client.RingerClient;
import voip.ringer.server.RingerServer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class DirectoryClient extends ListActivity  {
	 Socket serverSocket;
	 
	 ObjectOutputStream out;
	 ObjectInputStream in;
	 
	 User_Entry thisUser;
	 
	  ArrayAdapter<User_Entry> ad;

	 @Override
	public void onCreate(Bundle savedInstanceState) {
	  super.onCreate(savedInstanceState);
	  
      startService(new Intent(this, RingerServer.class));
      
		Bundle extras = getIntent().getExtras(); 

	    thisUser=new User_Entry(extras.getString("user_name"),extras.getString("ip_address"));

	  

	  this.connect();
	  this.populateList();
	  
	 this.getListView().setOnItemClickListener(new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
			// TODO Auto-generated method stub
			String selected = ((TextView)view).getText().toString();
			String userIP = selected.substring(selected.indexOf(":") + 1,selected.length());
			
			RingerClient rc = new RingerClient();
			
			   Intent myIntent = new Intent(DirectoryClient.this, rc.getClass());
			    myIntent.putExtra("recipient", selected.substring(0,selected.indexOf(":")));
			    myIntent.putExtra("User_IP", userIP);
			    
			    DirectoryClient.this.startActivity(myIntent);
			    
			    finish();
		}
		});

	}

	 
	    
	    @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.refresh_menu, menu);
	        return true;
	    }
	    
	    @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	            case R.id.refresh:     
				try {
					out.writeObject(new Packet(OPERATIONS.GET_USER_LIST));
					out.flush();
					@SuppressWarnings("unchecked")
					ArrayList<User_Entry> arrayList = (ArrayList<User_Entry>) in.readObject();
				/*	for(int i = 0; i < arrayList.size(); i++){
						Log.d("GAHH","OUSTIDE LOOP");
						if(!(((User_Entry)(arrayList.get(i))).getName().equals(thisUser.getName()))){
							Log.d("GAHH","ADDING");
							this.ad.add(((User_Entry)(arrayList.get(i))));
						}
					}*/
					this.getListView().setAdapter(new ArrayAdapter<User_Entry>(this.getApplicationContext(), android.R.layout.simple_list_item_1, arrayList));
					this.ad.setNotifyOnChange(true);
					ad.setNotifyOnChange(true);
					ad.notifyDataSetChanged();

					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	            break;
	      
	        }
	        return true;
	    }
	//Set the ipaddress
	public  void connect(){
		try {
			
			Bundle extras = getIntent().getExtras(); 
			serverSocket = new Socket();
			InetAddress inet = InetAddress.getByName(extras.getString("ip_address"));
			SocketAddress sa = new InetSocketAddress(inet, 4444);
			serverSocket.connect(sa);
			
			
			 out = new ObjectOutputStream(this.serverSocket.getOutputStream());
			 in = new ObjectInputStream(this.serverSocket.getInputStream());
			 
			 
			Packet initialSent = new Packet(OPERATIONS.INITIAL_ENTRY);
			initialSent.setContents(new User_Entry(extras.getString("user_name"), ""));
			 out.writeObject(initialSent); 	//Send initial packet
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.v("DEUBG, ",e.getMessage());
			e.printStackTrace();
		}
	}
	

	protected void populateList() {
		try {


			//Write request for the arraylist
			out.writeObject(new Packet(OPERATIONS.GET_USER_LIST));
			try {
				
				@SuppressWarnings("unchecked")
				ArrayList<User_Entry> arrayList = (ArrayList<User_Entry>) in.readObject();				  
				ListView lv = this.getListView();
				this.ad = new ArrayAdapter<User_Entry>(this.getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
				ad.setNotifyOnChange(true);
				lv.setAdapter(ad);
				//View.inflate(this.getApplicationContext(), R.layout.simple_list_item_1, null);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (StreamCorruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}


	//Connect to the server and grab an arraylist of possible addresses
	private void connectToServer() {
		// TODO Auto-generated method stub
		
	}
}
